%%%----------------------------------------------------------------------
%%% File    : cus_ejabberd_c2s.erl
%%% Author  : chen.kangmin
%%%----------------------------------------------------------------------

-module(cus_migrate).
-author('chen.kangmin').


-include("cus.hrl").
-include("cus_pb.hrl").
-include("ejabberd.hrl").
-include("logger.hrl").

%% External exports
-export([
    migrate/0,
    do_migrate/1
        ]
       ).


migrate() ->
    [Version, Node] = cus_config:migrate(),
    case node() of
        Node ->
            do_migrate(Version);
        _ ->
            skip
    end.


do_migrate(<<"1.0.0">>) ->
    migrate_user_emotion(),
    migrate_conversation_info(),
    ok;
do_migrate(_Version) ->
    skip.



migrate_user_emotion() ->
    cus_mysql:start('old_xiaoquan_im', "localhost", 3307, "root", "111111", "xiaoquan-im", utf8, 10),
    Data = cus_mysql:get_all('old_xiaoquan_im', "select id, emotions from cus_user"),
    lists:foreach(fun([Uid, Emotions]) ->
                          Info = #cus_user{uid = ?b2l(Uid),
                                           emotions = b2t(Emotions)},
                          cus_redis:set_user_info(Info)
                  end, Data),
    cus_mysql:remove_pool('old_xiaoquan_im').


migrate_conversation_info() ->
    Data = cus_mysql:get_all("select BrandSpaceID, BrandSpaceName from BrandSpaceInfo"),
    get_conversation_info(Data).


get_conversation_info([]) ->
    success;
get_conversation_info([[QuanId, Name] | T]) ->
    SelectMembers = io_lib:format("select BrandSpaceMemberUserID from BrandSpaceMemberInfo where BrandSpaceID = '~p' and BrandSpaceMemberStatus = 3", [QuanId]),
    case cus_mysql:get_all(SelectMembers) of
        [] ->
            undefined;
        Data ->
            Cid = "Q_" ++ ?i2l(QuanId),
            Members = lists:foldl(fun([Item], Acc) ->
                                          Uid = ?i2l(Item),
                                          cus_user:add_conversation(Uid, Cid, 0),
                                          [Uid | Acc]
                                  end, [], Data),
            Info = #cus_conversation{cid = Cid,
                                     name = ?b2l(Name),
                                     members = Members},
            cus_redis:set_conversation_info(Info)
    end,
    get_conversation_info(T).
    


b2t(undefined) -> [];
b2t(X)-> cus_util:bitstring_to_term(X).